﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Projecturo.Model;
using Projecturo.ProjecturoClient.Connection;
using Neits.PersistenceService.Providers;

namespace Projecturo.ProjecturoClient.ViewModel
{
    public static class TicketStateHelper
    {
        public static IList<TicketState> LoadTicketStates(Model.Project project, Ticket ticket, bool enableFilter)
        {
            IList<TicketState> ticketStates = new List<TicketState>();
            if (project != null)
            {
                var filter = new HqlFilter("from TicketState ts where ts.Project.Id = " + project.Id);
                ticketStates = Connector.Connectivity.Storage.GetList<TicketState>(filter);
                if (enableFilter)
                    FilterTicketStates(ticketStates, ticket, project);
            }
            return ticketStates;
        }

        private static void FilterTicketStates(IList<TicketState> states, Ticket ticket, Model.Project project)
        {
            if (ticket == null || ticket.State == null)
                return;

            var filter = new HqlFilter("from TicketStateMapping tsm where tsm.State.Project.Id = " + project.Id + " and tsm.State.Id = " + ticket.State.Id);
            IList<TicketStateMapping> mappings = Connector.Connectivity.Storage.GetList<TicketStateMapping>(filter);

            if (mappings.Count > 0)
            {
                var statesToRemove = new List<TicketState>();
                var tempStates = new List<TicketState>(states);

                foreach (var mapping in mappings)
                {
                    if (!mapping.IsAllowed)
                    {
                        TicketStateMapping stateMapping = mapping;
                        statesToRemove.Add(tempStates.Find(ts => ts.Id == stateMapping.MappingState.Id));
                    }
                }

                foreach (var ts in statesToRemove)
                    states.Remove(ts);
            }
        }
    }
}
